﻿using System;
using Core.DeviceProtocol;
using Core.Model;
using Core.Msg;

namespace CommonDeviceProtocol
{
    /// <summary>
    /// 通用协议
    /// </summary>
    public class CommonDeviceProtocol : BaseDevProtocol
    {
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="operid">命令Id</param>
        /// <returns></returns>
        public override RxTxCommand PostToExcute(string operid)
        {
            if (Operations.ContainsKey(operid))
            {
                Operation oper = DealOperationWithPara(Operations[operid], null); // 处理地址
                RxTxCommand cmd = new RxTxCommand(Dev.ChannelId,Dev.Id, oper.Name);
                cmd.IsAscii = oper.IsAscii;
                cmd.SendBytes = oper.MsgBuffer;
                cmd.NeedReply = oper.NeedReply;
                cmd.Timeout = oper.Timeout;
                cmd.DealReceiveMsg += Cmd_DealReceiveMsg;
                return cmd;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 带参数执行命令
        /// </summary>
        /// <param name="operid">命令Id</param>
        /// <param name="paras">参数集合</param>
        /// <returns></returns>
        public override RxTxCommand PostToExcute(string operid, string[] paras)
        {
            if (Operations.ContainsKey(operid))
            {
                Operation oper = DealOperationWithPara(Operations[operid],paras);
                RxTxCommand cmd = new RxTxCommand(Dev.ChannelId, Dev.Id, oper.Name);
                cmd.IsAscii = oper.IsAscii;
                cmd.NeedReply = oper.NeedReply;
                cmd.Timeout = oper.Timeout;
                cmd.SendBytes = oper.MsgBuffer;
                cmd.DealReceiveMsg += Cmd_DealReceiveMsg;
                return cmd;
            }
            else
            {
                return null;
            }
        }

        public override RxTxCommand WriteValue(string dataId, double value)
        {
            throw new NotImplementedException();
        }

        public override RxTxCommand WriteValue(string startId, byte[] buffer)
        {
            throw new NotImplementedException();
        }

        public override RxTxCommand RemoteControl(string rcId, bool @on)
        {
            throw new NotImplementedException();
        }

        private void Cmd_DealReceiveMsg(object sender, EventArgs e)
        {
            RxTxCommand cmd = sender as RxTxCommand;
            if (cmd!=null)
            {
                Console.WriteLine("接收:"+cmd.ReceiveMsg);
            }
        }
    }
}
